<template>
  <div class="crud-opts">
    <span class="crud-flex">
      <!--左侧插槽-->
      <slot name="left"/>
      <img class="img" src="@images/update.png" alt="" @click="doReply()">
      <!--更多操作-->
      <el-popover v-if="checkPermission(['appJob:del', 'appJob:edit', 'appJob:copy', 'appJob:rerun'])"
                  placement="bottom"
                  width="210" style="height:30px" trigger="click">
        <img class="img" slot="reference" src="@images/more.png" alt="">
        <div>
          <el-row v-if="checkPermission(['appJob:del'])">
            <el-col :span="12" style="margin-top: 5px;">
              <el-row>
                <label>常规操作</label>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-button v-permission="permission.del==undefined ? ['']:permission.del"
                           :disabled="crud.selections.length == 0" type="text" :loading="crud.delAllLoading"
                           @click="toDelete(crud.selections)">删除</el-button>
              </el-row>
            </el-col>
          </el-row>
          <el-row v-if="checkPermission(['appJob:edit', 'appJob:copy', 'appJob:rerun'])">
            <el-col :span="12" style="margin-top: 5px;">
              <el-row>
                <label>批量操作</label>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-button v-permission="permission.edit==undefined ? ['']:permission.edit"
                           :disabled="crud.selections.length == 0" type="text" :loading="crud.delAllLoading"
                           @click="changeBizDate(crud.selections)">修改业务日期</el-button>
              </el-row>
              <el-row>
                <el-button v-permission="permission.copy==undefined ? ['']:permission.copy"
                           :disabled="crud.selections.length == 0" type="text" :loading="crud.delAllLoading"
                           @click="crud.toCopy(crud.selections)">复制作业/任务</el-button>
              </el-row>
              <el-row>
                <el-button v-permission="permission.copy==undefined ? ['']:permission.copy"
                           :disabled="crud.selections.length == 0" type="text" :loading="crud.delAllLoading"
                           @click="chasingData(crud.selections)">追数作业/任务</el-button>
              </el-row>
              <el-row>
                <el-button v-permission="permission.rerun==undefined ? ['']:permission.rerun"
                           :disabled="crud.selections.length == 0" type="text" :loading="crud.delAllLoading"
                           @click="runAgainOne(crud.selections)">重跑作业/任务</el-button>
              </el-row>
            </el-col>
          </el-row>
        </div>
      </el-popover>
      <el-popover placement="bottom-end" width="150" style="height:30px" trigger="click">
        <img class="img" aria-hidden="true" slot="reference" src="@images/gezi.png" alt="">
        <el-checkbox v-model="allColumnsSelected" :indeterminate="allColumnsSelectedIndeterminate"
                     @change="handleCheckAllChange">
          全选
        </el-checkbox>
        <el-checkbox v-for="(item,i) in crud.props.tableColumns" :key="i" v-model="item.visible"
                     @change="handleCheckedTableColumnsChange(item)">
          {{ item.label }}
        </el-checkbox>
      </el-popover>
      <el-popover placement="bottom-start" width="888" style="height:30px" trigger="click" ref="popoverName">
        <img class="img" slot="reference" src="@images/shaixuan.png" alt="">
        <div>
          <el-form ref="form" :model="queryForm" label-position="right" label-width="100px"
                   style="max-height: 310px;overflow-y: auto;">
            <div v-for="(item, index) in moreQueryList" :key="index">
              <el-row v-if="item.type == 'textarea'">
                <el-col :span="14">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-input type="textarea" :rows="2" :placeholder="item.placeholder"
                              v-model.trim="queryForm[item.cloumLable]" style="width: 400px;"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="item.type == 'input'">
                <el-col :span="14">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-input v-model.trim="queryForm[item.cloumLable]" :placeholder="item.placeholder"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="item.type == 'select'">
                <el-col :span="14">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-select v-model="queryForm[item.cloumLable]" :placeholder="item.placeholder">
                      <el-option v-for="(ob,i) in allApp" :key="i" :label="ob.appName" :value="ob.appCode">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="item.type == 'radio'">
                <el-col :span="20">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-radio-group v-model="queryForm[item.cloumLable]" size="medium">
                      <el-radio-button v-for="(ob,i) in item.radioList" :key="i"
                                       :label="ob.label">{{ ob.value }}</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="item.type == 'datePicker'">
                <el-col :span="14">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-date-picker v-model="queryForm[item.cloumLable]" @change="dateChange(item.cloumLable)"
                                    value-format="yyyyMMdd" type="date" placeholder="选择日期" style="width: 400px;"/>
                  </el-form-item>
                </el-col>
                <el-col :span="10" style="padding-left: 20px;line-height: 33px;">
                  <el-radio v-model="queryForm[item.cloumLableType]" @change="fastDate(item.cloumLable,index * 10 + 0)"
                            :label="index * 10 + 0">今天</el-radio>
                  <el-radio v-model="queryForm[item.cloumLableType]" @change="fastDate(item.cloumLable,index * 10 + 1)"
                            :label="index * 10 + 1">昨天</el-radio>
                  <el-radio v-model="queryForm[item.cloumLableType]" @change="fastDate(item.cloumLable,index * 10 + 2)"
                            :label="index * 10 + 2">前天</el-radio>
                </el-col>
              </el-row>
              <el-row v-if="item.type == 'dateNoTimePicker'">
                <el-col :span="14">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-date-picker v-model="queryForm[item.cloumLable]" @change="dateChange(item.cloumLable)"
                                    value-format="yyyyMMdd" type="daterange" range-separator="至"
                                    start-placeholder="开始时间" end-placeholder="结束时间" style="width: 400px;"/>
                  </el-form-item>
                </el-col>
                <el-col :span="10" style="padding-left: 20px;line-height: 33px;">
                  <el-radio v-model="queryForm[item.cloumLableType]"
                            @change="selectDateFramePicker(item.cloumLable,index * 10 + 0)"
                            :label="index * 10 + 0">本周</el-radio>
                  <el-radio v-model="queryForm[item.cloumLableType]"
                            @change="selectDateFramePicker(item.cloumLable,index * 10 + 1)"
                            :label="index * 10 + 1">本月</el-radio>
                </el-col>
              </el-row>
              <el-row v-if="item.type == 'timeFramePicker'">
                <el-col :span="14">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-date-picker v-model="queryForm[item.cloumLable]" @change="dateTimeRangeChange(item.cloumLable)"
                                    value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至"
                                    start-placeholder="开始时间" end-placeholder="结束时间"/>
                  </el-form-item>
                </el-col>
                <el-col :span="10" style="padding-left: 20px;line-height: 33px;">
                  <el-radio v-model="queryForm[item.cloumLableType]"
                            @change="selectTimeFramePicker(item.cloumLable,index * 10 + 0)"
                            :label="index * 10 + 0">今天</el-radio>
                  <el-radio v-model="queryForm[item.cloumLableType]"
                            @change="selectTimeFramePicker(item.cloumLable,index * 10 + 1)"
                            :label="index * 10 + 1">昨天</el-radio>
                  <el-radio v-model="queryForm[item.cloumLableType]"
                            @change="selectTimeFramePicker(item.cloumLable,index * 10 + 2)"
                            :label="index * 10 + 2">本周</el-radio>
                  <el-radio v-model="queryForm[item.cloumLableType]"
                            @change="selectTimeFramePicker(item.cloumLable,index * 10 + 3)"
                            :label="index * 10 + 3">本月</el-radio>
                </el-col>
              </el-row>
            </div>
          </el-form>
          <el-row style="border-top: 1px solid #EBEEF5;padding-top: 10px;text-align: center;">
            <el-button @click="doReset" style="width: 80px;">重置</el-button>
            <el-button type="primary" @click="doMoreQuery" style="width: 80px;">查询</el-button>
          </el-row>
        </div>
      </el-popover>
      <!--右侧-->
      <slot name="right"/>
    </span>
    <el-button-group class="crud-opts-right">
      <el-pagination :page-size.sync="page.size" :total="page.total" :page-sizes="[10, 50, 100, 300, 500, 1000]"
                     :current-page.sync="page.page" style="margin-top: 8px;" layout="prev, pager, next,sizes,total"
                     @size-change="crud.sizeChangeHandler($event)" @current-change="crud.pageChangeHandler"
                     :pager-count="5" prev-text=" " next-text=" "/>
    </el-button-group>

    <el-dialog append-to-body :close-on-click-modal="false"
               :before-close="cancelCU"
               :visible.sync="chasingDataFlag"
               title="追数作业/任务" width="680px">
      <el-form ref="form" :inline="true" :model="chasingDataForm" size="small" label-width="160px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="作业状态" prop="jobCopyStatus">
              <el-select v-model="chasingDataForm.jobCopyStatus" filterable placeholder="请选择" @change="jobCopyStatusChange">
                <el-option v-for="item in this.dict.cycle_job_status" :key="item.value" :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="业务日期">
              <el-date-picker v-model="chasingDataForm.bizDates" type="daterange" range-separator="至" value-format="yyyy-MM-dd"
                              start-placeholder="开始日期" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-document-delete" @click="cancelCU">取消</el-button>
        <el-button icon="el-icon-document-add" :loading="chasingDataLoading" type="primary" @click="submitChasingDataForm">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CRUD, {crud, pagination} from "@crud/crud";
import {MessageBox} from "element-ui";
import periodJobApi from "@/api/cycleJob/job";
import config from '@/settings'
import checkPermission from '@/utils/permission'
import {chasingData} from "../../../../../../api/cycleJob/job"; // 权限判断函数

const dateOffset = config.dateOffset

export default {
  mixins: [crud(), pagination()],
  dicts: ['cycle_job_status'],
  filters: {
    formatTime: function (value) {
      if (value != '') {
        return value.slice(0, 19).replace('T', ' ')
      }
    }
  },
  props: {
    permission: {
      type: Object,
      default: null
    },
    moreQueryList: null,
    allApp: []
  },
  data() {
    return {
      chasingDataFlag: false,
      chasingDataLoading: false,
      chasingDataForm: {
        bizDates: [],
        pkIds: [],
        jobCopyStatus: null
      },
      defaultQueryForm: {
        bizDate: '',
        jobCode: null,
        jobName: null,
        jobStatus: '',
        bz: null,
        startTime: [],
        endTime: []
      },
      allColumnsSelected: true,
      allColumnsSelectedIndeterminate: false,
      qryParam: "",
      qryCloum: "",
      queryForm: {},
    };
  },
  created() {
    this.crud.updateProp("searchToggle", true);
    if (this.crud.params.bizDate == '' || this.crud.params.bizDate) {
      this.queryForm = this.crud.params
    } else {
      this.queryForm = JSON.parse(JSON.stringify(this.defaultQueryForm));
    }
  },
  methods: {
    checkPermission,
    init() {
      this.crud.query.bizDate = this.currentDate()
      this.crud.toQuery()
    },
    cancelCU(){
      this.chasingDataFlag = false
    },
    chasingData(data){
      let bizDate = data[0].bizDate
      for (let i = 0; i < data.length; i++) {
        if (bizDate != data[i].bizDate) {
          MessageBox.alert(`请选中相同业务日期的多条记录!`, '提示', {
            confirmButtonText: '确定',
            type: 'warning'
          })
          return false
        }
      }
      this.chasingDataForm.pkIds = []
      data.forEach(item => {
        this.chasingDataForm.pkIds.push(item.pkId);
      })
      this.chasingDataFlag = true
      return true
    },
    submitChasingDataForm(){
      this.$confirm(`确认追数选中周期作业吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.chasingDataLoading = true
        periodJobApi.chasingData(this.chasingDataForm).then(res=>{
          this.chasingDataLoading = false
          this.$notify({ title: '成功', message: '重跑启动成功！', type: 'success'});
          this.crud.toQuery();
        })
      }).catch(() => {
        this.chasingDataLoading = false
      });
    },
    jobCopyStatusChange(val) {
      return this.dict.label.cycle_job_status[val]
    },
    currentDate() {
      let timestamp = Date.now() + dateOffset * 1000 * 60 * 60 * 24
      let date = new Date(timestamp)
      let year = date.getFullYear()
      let month = ('0' + (date.getMonth() + 1)).slice(-2)
      let sdate = ('0' + date.getDate()).slice(-2)
      let result = year + month + sdate
      return result
    },
    toDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.crud.delAllLoading = true;
        this.crud.doDeleteByPkId(datas);
      }).catch(() => {
      });
    },
    changeBizDate(data) {
      // let bizDate = data[0].bizDate.substring(0,4) + "-" + data[0].bizDate.substring(4,6) + "-" + data[0].bizDate.substring(6,8);
      let bizDate = data[0].bizDate;
      for (let i = 0; i < data.length; i++) {
        if (bizDate != null && bizDate != data[i].bizDate) {
          MessageBox.alert(`请选中相同业务日期的多条记录!`, "提示", {
            confirmButtonText: "确定",
            type: "warning"
          });
          return;
        }
      }
      let formData = {selections: data, bizDate: bizDate}
      this.crud.editType.changeBizDate = true;
      this.crud.toEdit(formData);
    },
    runAgainOne(data) {
      this.$confirm(`确认重跑选中的${data.length}条数据吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let pkIds = [];
        data.forEach(item => {
          pkIds.push(item.pkId);
        })
        this.doRunAgainOne(pkIds);
      }).catch(() => {
      });
    },
    handleCheckAllChange(val) {
      if (val === false) {
        this.$message({
          message: '请至少选择一列',
          type: 'warning'
        });
        this.allColumnsSelected = true
        return
      }
      for (const key in this.crud.props.tableColumns) {
        this.crud.props.tableColumns[key].visible = val;
      }
      this.allColumnsSelected = val;
      this.allColumnsSelectedIndeterminate = false;
    },
    handleCheckedTableColumnsChange(item) {
      let totalCount = 0;
      let selectedCount = 0;
      for (const key in this.crud.props.tableColumns) {
        ++totalCount;
        selectedCount += this.crud.props.tableColumns[key].visible ? 1 : 0;
      }
      if (selectedCount === 0) {
        this.crud.notify("请至少选择一列", CRUD.NOTIFICATION_TYPE.WARNING);
        this.$nextTick(function () {
          item.visible = true;
        });
        return;
      }
      this.allColumnsSelected = selectedCount === totalCount;
      this.allColumnsSelectedIndeterminate =
        selectedCount !== totalCount && selectedCount !== 0;
    },
    doReply() {
      this.crud.findVM('presenter').$refs['table'].clearFilter()
      this.crud.query = {}
      this.qryParam = ''
      this.qryCloum = ''
      this.queryForm = JSON.parse(JSON.stringify(this.defaultQueryForm));
      this.crud.params = {}
      this.init()
    },
    fastDate(cloum, index) {
      index = index % 10;
      this.queryForm[cloum] = this.$moment().add(-index, 'days').format('YYYYMMDD');
    },
    selectTimeFramePicker(cloum, index) {
      index = index % 10;
      if (0 == index) {
        this.queryForm[cloum] = [];
        this.queryForm[cloum].push(this.$moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'));
        this.queryForm[cloum].push(this.$moment().endOf('day').format('YYYY-MM-DD HH:mm:ss'));
      }
      if (1 == index) {
        this.queryForm[cloum] = [];
        this.queryForm[cloum].push(this.$moment().add(-1, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss'));
        this.queryForm[cloum].push(this.$moment().add(-1, 'days').endOf('day').format('YYYY-MM-DD HH:mm:ss'));
      }
      if (2 == index) {
        this.queryForm[cloum] = [];
        this.queryForm[cloum].push(this.$moment().startOf('isoWeek').format('YYYY-MM-DD HH:mm:ss'));
        this.queryForm[cloum].push(this.$moment().endOf('day').format('YYYY-MM-DD HH:mm:ss'));
      }
      if (3 == index) {
        this.queryForm[cloum] = [];
        this.queryForm[cloum].push(this.$moment().startOf('month').format('YYYY-MM-DD HH:mm:ss'));
        this.queryForm[cloum].push(this.$moment().endOf('day').format('YYYY-MM-DD HH:mm:ss'));
      }
    },
    selectDateFramePicker(cloum, index) {
      index = index % 10;
      if (0 == index) {
        this.queryForm[cloum] = [];
        this.queryForm[cloum].push(this.$moment().startOf('isoWeek').format('YYYYMMDD'));
        this.queryForm[cloum].push(this.$moment().endOf('day').format('YYYYMMDD'));
      }
      if (1 == index) {
        this.queryForm[cloum] = [];
        this.queryForm[cloum].push(this.$moment().startOf('month').format('YYYYMMDD'));
        this.queryForm[cloum].push(this.$moment().endOf('day').format('YYYYMMDD'));
      }
    },
    doReset() {
      this.queryForm = JSON.parse(JSON.stringify(this.defaultQueryForm));
      this.doMoreQuery();
    },
    doMoreQuery() {
      this.$refs['popoverName'].doClose()
      this.crud.page.page = 1;
      this.crud.params = JSON.parse(JSON.stringify(this.queryForm));
      this.crud.toQuery();
    },
    dateChange(cloumLable) {
      let cloum = cloumLable + "Type";
      this.queryForm[cloum] = null;
    },
    dateTimeRangeChange(cloumLable) {
      let cloum = cloumLable + "Type";
      this.queryForm[cloum] = null;
    },
    doRunAgainOne(pkIds) {
      periodJobApi.runAgainOne(pkIds)
        .then(res => {
          this.$notify({
            title: '成功',
            message: '重跑启动成功！',
            type: 'success'
          });
          this.crud.toQuery();
        })
        .catch(err => {
          // this.$notify.error({title: '错误', message: '重跑启动失败'});
        });
      this.runAgainVisi = false;
    }
  }
};
</script>

<style>
.crud-opts {
  padding: 6px 0;
  display: -webkit-flex;
  display: flex;
  align-items: center;
}

.crud-opts .crud-opts-right {
  margin-left: auto;
}

.item .el-form-item__label {
  font-weight: 100;
}

.crud-opts-left {
  display: flex;
  align-items: center;
}
</style>
